import numpy as np
import time
from datetime import datetime
import random
from hsync.core.user_profile import UserProfile
from hsync.core.learning_engine import LearningEngine
from hsync.core.memory_pool import MemoryPool
from hsync.core.quantum_filter import QuantumFilterService
from hsync.core.counterfactual_reasoner import CounterfactualReasoner
from hsync.core.signal_gateway import SignalGateway
from hsync.compliance.gdpr_manager import GDPRCompliance

def generate_user_input(context):
    """生成模拟的用户输入文本"""
    work_inputs = [
        "请解释一下这个API的参数含义",
        "这个错误代码是什么意思？",
        "能否提供更高效的实现方案？",
        "这个函数的时间复杂度是多少？",
        "请简要说明系统架构"
    ]
    
    casual_inputs = [
        "嘿，这个怎么用啊？",
        "能简单说下吗？😂",
        "不太懂，能举个例子吗",
        "这个功能好棒啊！👍",
        "有没有更简单的方法？"
    ]
    
    learning_inputs = [
        "为什么这个算法要这样设计？",
        "请详细解释这个概念",
        "这个原理背后的理论基础是什么？",
        "我不太明白这一步，能再讲一遍吗？",
        "有什么推荐的学习资源吗？"
    ]
    
    if context == 'work':
        return random.choice(work_inputs)
    elif context == 'casual':
        return random.choice(casual_inputs)
    else:
        return random.choice(learning_inputs)

def generate_voice_input(context):
    """生成模拟的语音输入描述"""
    work_voices = [
        "请解释一下这个API的参数含义",
        "这个错误代码是什么意思",
        "能否提供更高效的实现方案",
        "这个函数的时间复杂度是多少"
    ]
    
    casual_voices = [
        "嘿，这个怎么用啊",
        "能简单说下吗",
        "不太懂，能举个例子吗",
        "这个功能好棒啊"
    ]
    
    learning_voices = [
        "为什么这个算法要这样设计",
        "请详细解释这个概念",
        "这个原理背后的理论基础是什么",
        "我不太明白这一步，能再讲一遍吗"
    ]
    
    if context == 'work':
        return random.choice(work_voices)
    elif context == 'casual':
        return random.choice(casual_voices)
    else:
        return random.choice(learning_voices)

def generate_feedback(behavior, response, correctness=0.8):
    """生成模拟的用户反馈"""
    # 基于行为和响应的匹配度生成反馈
    match_score = np.random.normal(0.7, 0.15) if random.random() < correctness else np.random.normal(0.3, 0.15)
    match_score = np.clip(match_score, 0.1, 0.95)
    
    # 生成文字反馈
    if match_score > 0.8:
        feedback_text = random.choice([
            "非常好，符合我的需求",
            "完美，这正是我想要的",
            "太贴心了，完全懂我",
            "很棒，继续保持这种风格"
        ])
        correction = 0
    elif match_score > 0.5:
        feedback_text = random.choice([
            "还不错，但可以更简洁一些",
            "基本符合，但希望更详细点",
            "还行，不过语气可以调整下",
            "不错，但有点偏离我的需求"
        ])
        correction = random.choice([-1, 0, 1])  # 轻微修正
    else:
        feedback_text = random.choice([
            "不太符合我的要求",
            "完全没理解我的意思",
            "希望能换一种方式解释",
            "这不是我想要的风格"
        ])
        correction = random.choice([-2, -1, 1, 2])  # 明显修正
    
    return {
        'score': match_score,
        'text': feedback_text,
        'correction': correction,
        'timestamp': datetime.now().timestamp()
    }

def generate_response(user_prefs):
    """基于用户偏好生成模拟响应"""
    detail_level = user_prefs['detail_level']
    formality = user_prefs['formality']
    context = user_prefs['context']
    
    # 根据详细程度调整长度
    if detail_level == 'concise':
        length_factor = 0.3
        details = "简要说明："
    elif detail_level == 'balanced':
        length_factor = 0.7
        details = "中等详细说明："
    else:  # detailed
        length_factor = 1.0
        details = "详细说明："
    
    # 根据正式程度调整语气
    if formality in ['very_casual', 'casual']:
        tone = random.choice([
            "嘿，", "你好呀，", "嗨，", ""
        ])
        emoji = random.choice(["😊", "👍", "", "✨"]) if random.random() < 0.5 else ""
    elif formality == 'neutral':
        tone = random.choice([
            "你好，", "您好，", ""
        ])
        emoji = ""
    else:  # formal, very_formal
        tone = random.choice([
            "您好，", "尊敬的用户，", ""
        ])
        emoji = ""
    
    # 根据情境生成内容
    if context == 'work':
        content = random.choice([
            "该功能主要用于处理数据转换，支持多种格式。",
            "这个API的参数包括输入路径、输出格式和处理模式。",
            "系统采用微服务架构，可扩展性强，适合企业级应用。",
            "该算法的时间复杂度为O(n log n)，空间复杂度为O(n)。"
        ])
    elif context == 'casual':
        content = random.choice([
            "这个很好用的，直接点一下就行啦~",
            "很简单的，你试试就知道了，超方便！",
            "这个功能不错吧，我也经常用呢~",
            "很容易上手的，几分钟就能学会"
        ])
    else:  # learning
        content = random.choice([
            "这个概念的核心在于理解变量之间的关系，首先需要掌握基础定义，然后通过实例练习加深理解。",
            "该原理基于三个基本假设：第一是连续性，第二是可加性，第三是对称性。",
            "学习这个知识点可以分为三个步骤：首先理解基本概念，然后掌握推导过程，最后通过应用巩固。",
            "推荐从基础教材开始，配合在线课程和实践项目，这样能更全面地掌握相关知识。"
        ])
    
    # 根据长度因子调整内容
    if length_factor < 0.5:
        # 更简洁
        content = content.split('，')[0] + "。"
    elif length_factor < 0.8:
        # 中等长度
        parts = content.split('，')
        content = "，".join(parts[:min(2, len(parts))]) + "。"
    
    return f"{tone}{details}{content}{emoji}"

def run_demo():
    """运行HSync架构完整演示"""
    print("=== HSync架构演示 ===")
    print("基于习惯养成机制的AI交互系统\n")
    user_id = "demo_user_001"
    
    # 初始化核心组件
    quantum_filter = QuantumFilterService(use_quantum_hardware=True)
    user_profile = UserProfile(user_id)
    learning_engine = LearningEngine(user_profile)
    memory_pool = MemoryPool()
    reasoner = CounterfactualReasoner(user_profile)
    signal_gateway = SignalGateway(quantum_filter)
    gdpr_manager = GDPRCompliance(epsilon=0.3)
    
    # 模拟多轮交互
    contexts = ['work', 'casual', 'learning', 'work', 'casual', 
                'work', 'learning', 'casual', 'learning', 'work']
    signal_types = ['text', 'voice', 'text', 'sensor', 'text', 
                   'voice', 'text', 'sensor', 'voice', 'text']
    
    for i in range(10):
        print(f"\n=== 交互轮次 {i+1} ===")
        
        # 选择情境和信号类型
        context = contexts[i % len(contexts)]
        signal_type = signal_types[i % len(signal_types)]
        print(f"情境: {context}, 信号类型: {signal_type}")
        
        # 生成用户输入
        if signal_type == 'text':
            user_input = generate_user_input(context)
        elif signal_type == 'voice':
            user_input = generate_voice_input(context)
        else:  # sensor
            user_input = "触摸交互"  # 传感器输入简单表示
        
        print(f"用户输入: {user_input}")
        
        # 处理信号
        processed_signal = signal_gateway.process_signal(
            user_input, signal_type, context
        )
        
        # GDPR合规处理
        compliant_data = gdpr_manager.process_data(
            processed_signal, 
            user_id, 
            data_type=f"signal_{signal_type}"
        )
        
        # 更新用户画像
        behavior_data = {
            'timestamp': processed_signal['timestamp'],
            'features': processed_signal['features'],
            'raw_input': user_input
        }
        
        updated = user_profile.update_from_behavior(behavior_data, context)
        if updated and i > 0:
            print("用户画像已更新")
        
        # 预测用户偏好
        user_prefs = user_profile.predict_preferences(processed_signal['features'])
        print(f"预测偏好: 详细度={user_prefs['detail_level']}, 正式度={user_prefs['formality']}, 置信度={user_prefs['confidence']:.2f}")
        
        # 记录AI决策（ISO/IEC 23894合规）
        decision_id = gdpr_manager.log_ai_decision({
            'type': 'response_generation',
            'inputs': processed_signal['features'].tolist(),
            'output': user_prefs,
            'confidence': user_prefs['confidence']
        })
        
        # 生成响应
        response = generate_response(user_prefs)
        print(f"AI响应: {response}")
        
        # 生成用户反馈
        feedback = generate_feedback(behavior_data, response)
        print(f"用户反馈: {feedback['text']} (评分: {feedback['score']:.2f})")
        
        # 学习引擎从反馈中学习
        learning_result = learning_engine.learn_from_feedback(
            feedback, processed_signal['features'], importance=min(1.0, feedback['score'] * 1.2)
        )
        if learning_result['conflict_detected']:
            print("检测到梯度冲突并已解决")
        
        # 存储记忆
        memory_id = memory_pool.store_memory(
            user_id,
            {
                'user_input': user_input,
                'response': response,
                'feedback': feedback['score'],
                'context': context,
                'signal_type': signal_type
            },
            importance=feedback['score'],
            context={'domain': context, 'signal_type': signal_type},
            embedding=processed_signal['features'][:100]  # 使用特征作为嵌入
        )
        
        # 检测异常行为
        anomaly_score, anomaly_features = reasoner.detect_anomalies(
            processed_signal['features'], context
        )
        
        if anomaly_score > 0.8:  # 异常分数阈值
            print(f"检测到异常行为 (分数: {anomaly_score:.2f})")
            possible_causes = reasoner.reason_about_anomaly(
                processed_signal['features'], context, anomaly_features
            )
            
            if possible_causes:
                print("可能的原因:")
                for cause, conf in possible_causes[:3]:
                    print(f"  - {cause}: {conf:.2f}")
                
                # 生成澄清问题
                clarification = reasoner.generate_clarification(possible_causes, context)
                print(f"澄清问题: {clarification}")
        
        # 每3轮检索一次相关记忆
        if i > 0 and i % 3 == 0:
            print("\n检索相关记忆:")
            memories = memory_pool.retrieve_memory(
                user_id,
                query_embedding=processed_signal['features'][:100],  # 使用前100维作为查询嵌入
                context={'domain': context},
                top_n=2
            )
            for j, mem in enumerate(memories):
                print(f"  记忆 {j+1}: 用户输入='{mem['data']['user_input']}', 反馈评分={mem['data']['feedback']:.2f}")
        
        # 稍作等待，模拟真实交互间隔
        time.sleep(0.5)
    
    # 展示最终统计信息
    print("\n=== 演示统计信息 ===")
    print("记忆池统计:", memory_pool.get_stats())
    print("滤波性能:", quantum_filter.get_performance_metrics())
    print("信号处理统计:", signal_gateway.get_routing_stats())
    print("推理统计:", reasoner.get_reason_stats())
    print("学习统计:", learning_engine.get_learning_stats())
    print("用户画像摘要:", user_profile.get_profile_summary())

if __name__ == "__main__":
    run_demo()
    